package router

import "github.com/gin-gonic/gin"

func getAllMessage(c *gin.Context) {
	stmt, err := db.Prepare("SELECT * FROM message")
	if err != nil {
		c.Error(err)
	}
	rows, err := stmt.Query()
	messages := make([]message, 0)
	for rows.Next() {
		var mes message
		rows.Scan(&mes.Id, &mes.Content, &mes.Name, &mes.Time)
		messages = append(messages, mes)
	}
	c.JSON(200, gin.H{
		"list": messages,
	})
}

func createMessage(c *gin.Context) {
	var mes message
	c.ShouldBindJSON(&mes)
	stmt, err := db.Prepare("INSERT INTO message (`content`,`name`,`time`) VALUES  (?,?,?)")
	if err != nil {
		c.Error(err)
	}
	_, err = stmt.Exec(mes.Content, mes.Name, mes.Time)
	if err != nil {
		c.Error(err)
	}
	c.JSON(200, gin.H{})
}

func delMessageById(c *gin.Context) {
	id := c.Query("id")
	stmt, err := db.Prepare("DELETE FROM message WHERE id = ?")
	if err != nil {
		c.Error(err)
	}
	_, err = stmt.Exec(id)
	if err != nil {
		c.Error(err)
	}
	c.JSON(200, gin.H{})
}

func getAllMessageComment(c *gin.Context) {
	stmt, err := db.Prepare("SELECT * FROM messageComment")
	if err != nil {
		c.Error(err)
	}
	rows, err := stmt.Query()
	if err != nil {
		c.Error(err)
	}
	messageComments := make([]messageComment, 0)
	for rows.Next() {
		var com messageComment
		rows.Scan(&com.Id, &com.MessageId, &com.Content, &com.Name, &com.Time)
		messageComments = append(messageComments, com)
	}
	c.JSON(200, gin.H{
		"list": messageComments,
	})
}

//传入message的id
func getAllMessageCommentById(c *gin.Context) {
	messageId := c.Query("messageId")
	stmt, err := db.Prepare("SELECT * FROM messageComment WHERE messageId = ?")
	if err != nil {
		c.Error(err)
	}
	rows, err := stmt.Query(messageId)
	if err != nil {
		c.Error(err)
	}
	messageComments := make([]messageComment, 0)
	for rows.Next() {
		var com messageComment
		rows.Scan(&com.Id, &com.MessageId, &com.Content, &com.Name, &com.Time)
		messageComments = append(messageComments, com)
	}
	c.JSON(200, gin.H{
		"list": messageComments,
	})
}

func createMessageComment(c *gin.Context) {
	var com messageComment
	c.ShouldBindJSON(&com)
	stmt, err := db.Prepare("INSERT INTO messageComment (`messageId`,`content`,`name`,`time`) VALUES (?,?,?,?)")
	if err != nil {
		c.Error(err)
	}
	_, err = stmt.Exec(com.MessageId, com.Content, com.Name, com.Time)
	if err != nil {
		c.Error(err)
	}
	c.JSON(200, gin.H{})
}

func delMessageCommentById(c *gin.Context) {
	id := c.Query("id")
	stmt, err := db.Prepare("DELETE FROM messageComment WHERE `id` = ?")
	if err != nil {
		c.Error(err)
	}
	_, err = stmt.Exec(id)
	if err != nil {
		c.Error(err)
	}
	c.JSON(200, gin.H{})
}

func InitMessage(e *gin.Engine) {
	g := e.Group("/message")
	g.POST("/getAllMessage", getAllMessage)
	g.POST("/createMessage", createMessage)
	g.POST("/delMessageById", delMessageById)
	g.POST("/getAllMessageCommentById", getAllMessageCommentById)
	g.POST("/createMessageComment", createMessageComment)
	g.POST("/delMessageCommentById", delMessageCommentById)
}
